﻿Imports FuncClasses
Imports System.Security.Cryptography

Public Class NewCompanyWelcomePage

    ''' <summary>
    ''' Go to second tab
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub NewCompanyResume_Click(sender As Object, e As RoutedEventArgs) Handles NewCompanyResume.Click
        dbtab.Visibility = Windows.Visibility.Visible
        tabcontrol.SelectedValue = dbtab
    End Sub

    ''' <summary>
    ''' Go to third tab
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button_Click_1(sender As Object, e As RoutedEventArgs)
        usrtab.Visibility = Windows.Visibility.Visible
        tabcontrol.SelectedValue = usrtab
    End Sub

    ''' <summary>
    ''' Finish and save
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button_Click_2(sender As Object, e As RoutedEventArgs)
        Dim db As IDatabase
        _gotoimport = ToggleImport.IsChecked
        'Set Database first
        If rb_localdb.IsChecked Then
            Dim dbpath As String = tb_localdbdirectory.Text
            If String.IsNullOrEmpty(dbpath) Then
                dbpath = System.AppDomain.CurrentDomain.BaseDirectory()
            End If

            Dim dbtype As String = ""
            Select Case cb_ldbs.SelectedIndex
                Case 0
                    dbtype = "FastXML"
                    db = New FastXML(dbpath)
                Case 1
                    dbtype = "SQLite"
                    db = New FluentNHibernateConnector(Window1.AppID, dbpath, Dispatcher, dbtype)
            End Select

            Dim path As String = System.AppDomain.CurrentDomain.BaseDirectory() + "database.xml"
            Dim doc As XElement
            If IO.File.Exists(path) = False Then
                doc = New XElement("database")
            Else
                doc = XElement.Load(path)
            End If
            doc.SetAttributeValue("directory", dbpath)
            doc.SetAttributeValue("name", dbtype)
            'save
            doc.Save(path)

            AddHandler db.DatabaseConnected, AddressOf SetUpDatabase
            AddHandler db.DatabaseNotConnected, AddressOf DatabaseNotConnected
            db.Connect()
        Else
            Dim dbtype As String = ""
            Select Case cb_dbs.SelectedIndex
                Case 0
                    dbtype = "MySQL"
                Case 1
                    dbtype = "MsSQL2008"
                Case 2
                    dbtype = "MsSQL2012"
                Case 3
                    dbtype = "PostgreSQL"
                Case 4
                    dbtype = "DB2"
            End Select

            Dim path As String = System.AppDomain.CurrentDomain.BaseDirectory() + "\database.xml"
            Dim doc As XElement
            If IO.File.Exists(path) = False Then
                doc = New XElement("database")
            Else
                doc = XElement.Load(path)
            End If
            doc.SetAttributeValue("name", dbtype)
            doc.SetAttributeValue("dbserver", tb_dbserver.Text)
            doc.SetAttributeValue("dbname", tb_dbdbname.Text)
            doc.SetAttributeValue("dbuser", tb_dbuser.Text)
            doc.SetAttributeValue("dbuserpasswd", tb_dbuserpasswd.Password)
            'save
            doc.Save(path)
            db = New FluentNHibernateConnector(Window1.AppID, tb_dbserver.Text, tb_dbdbname.Text, tb_dbuser.Text, tb_dbuserpasswd.Password, Dispatcher, dbtype)
            AddHandler db.DatabaseConnected, AddressOf SetUpDatabase
            AddHandler db.DatabaseNotConnected, AddressOf DatabaseNotConnected
            db.Connect()
        End If
        SP_DBQuery2.Visibility = Windows.Visibility.Visible
    End Sub

    Private _companyname As String
    Private _gotoimport As Boolean
    Private _usr As User
    Private _db As IDatabase

    Public ReadOnly Property CompanyName As String
        Get
            Return _companyname
        End Get
    End Property

    Public ReadOnly Property GoToImport As Boolean
        Get
            Return _gotoimport
        End Get
    End Property

    Public ReadOnly Property User As User
        Get
            Return _usr
        End Get
    End Property

    Public ReadOnly Property Database As IDatabase
        Get
            Return _db
        End Get
    End Property

    Private Function GetHash(input As String) As String
        Dim dataToMAC As Byte() = System.Text.Encoding.UTF8.GetBytes(input)
        Using hmacsha1 As New HMACSHA256(System.Text.Encoding.UTF8.GetBytes("EBFD359A91C23FEC2E3267D5FAE87A37F7156C0B0524CBDE533225F10605C913"))
            Return System.Convert.ToBase64String(hmacsha1.ComputeHash(dataToMAC))
        End Using
    End Function

    Public Event DatabaseSet()

    ''' <summary>
    ''' Check nhibernate database
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button_Click_3(sender As Object, e As RoutedEventArgs)
        Dim dbtype As String = ""
        Select Case cb_dbs.SelectedIndex
            Case 0
                dbtype = "MySQL"
            Case 1
                dbtype = "MsSQL2008"
            Case 2
                dbtype = "MsSQL2012"
            Case 3
                dbtype = "PostgreSQL"
            Case 4
                dbtype = "DB2"
        End Select
        Dim t = New FluentNHibernateConnector(Window1.AppID, tb_dbserver.Text, tb_dbdbname.Text, tb_dbuser.Text, tb_dbuserpasswd.Password, Dispatcher, dbtype)
        AddHandler t.DatabaseError, AddressOf dberror
        AddHandler t.DatabaseNotConnected, AddressOf DatabaseNotConnected
        AddHandler t.DatabaseConnected, AddressOf DatabaseConnected
        t.Connect()
        SP_DBQuery.Visibility = Windows.Visibility.Visible
    End Sub

    Private Sub dberror(msg As String)
        'MessageBox.Show(msg)
    End Sub

    ''' <summary>
    ''' GetCompanyList
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button_Click_4(sender As Object, e As RoutedEventArgs)
        SP_DBQuery.Visibility = Windows.Visibility.Visible
        Dim db As IDatabase
        If rb_localdb.IsChecked Then
            Dim dbpath As String = tb_localdbdirectory.Text
            Dim dbtype As String = ""
            Select Case cb_ldbs.SelectedIndex
                Case 0
                    dbtype = "FastXML"
                    db = New FastXML(dbpath)
                Case 1
                    dbtype = "SQLite"
                    db = New FluentNHibernateConnector(Window1.AppID, dbpath, Dispatcher, dbtype)
            End Select
        Else
            Dim dbtype As String = ""
            Select Case cb_dbs.SelectedIndex
                Case 0
                    dbtype = "MySQL"
                Case 1
                    dbtype = "MsSQL2008"
                Case 2
                    dbtype = "MsSQL2012"
                Case 3
                    dbtype = "PostgreSQL"
                Case 4
                    dbtype = "DB2"
            End Select
            db = New FluentNHibernateConnector(Window1.AppID, tb_dbserver.Text, tb_dbdbname.Text, tb_dbuser.Text, tb_dbuserpasswd.Password, Dispatcher, dbtype)
        End If
        AddHandler db.DatabaseConnected, AddressOf GetCompanyList
        AddHandler db.DatabaseNotConnected, AddressOf DatabaseNotConnected
        db.Connect()
    End Sub

    Private Sub GetCompanyList(src As IDatabase)
        LV_ChooseCompany.ItemsSource = src.GetAllCompanys
        SP_DBQuery.Visibility = Windows.Visibility.Hidden
    End Sub

    Private Sub SetUpDatabase(db As IDatabase)
        If TypeOf db Is FluentNHibernateConnector Then
            db.SaveOrUpdatePaymentMethode(Nothing)
        End If
        Dim csettings = New nHibernate.Models.CompanySettingsModel With {.CompanyName = NewCompanyName.Text, .Street = NewCompanyStreet.Text, .No = NewCompanyNo.Text, .ZipCode = NewCompanyZip.Text, _
                                                                                            .City = NewCompanyCity.Text, .Country = NewCompanyCountry.Text, .Addition = NewCompanyAddressAddition.Text, .IsIDNumeric = True, .CompanyID = Guid.NewGuid.ToString}
        If LV_ChooseCompany.SelectedIndex > -1 AndAlso cb_ChooseComapany.IsChecked Then
            _companyname = LV_ChooseCompany.SelectedItem.CompanyName
        Else
            _companyname = NewCompanyName.Text
            'Save Companyaddress
            db.SaveOrUpdateCompanySettings(csettings)
        End If

        'User
        Dim usr As User
        If rb_remotedb.IsChecked AndAlso Not String.IsNullOrEmpty(tb_eusrname.Text) Then
            usr = New User(tb_eusrname.Text, tb_euserpasswd.Password, db)
        Else
            Try
                Dim hash As String = GetHash(tb_usrname.Text + tb_userpasswd.Password + ("truetruetruetruetruetruetruetruetrue"))
                Dim user As New nHibernate.Models.UserPreviewModel With {.Hash = hash, .UserName = tb_usrname.Text, .UserID = tb_userid.Text, .CanEditUsers = True, .CanReadArticle = True, .CanReadCustomer = True, .CanReadDatabase = True, _
                                                                         .CanReadOrder = True, .CanWriteArticle = True, .CanWriteCustomer = True, .CanWriteDatabase = True, .CanWriteOrder = True}
                db.SaveOrUpdateUser(user, Nothing)
            Catch : End Try
            usr = New User(tb_usrname.Text, tb_userpasswd.Password, db)
        End If

        If usr.LogInFailed Then
            lbl_usrfailed.Visibility = Windows.Visibility.Visible
            Dim path As String = System.AppDomain.CurrentDomain.BaseDirectory() + "database.xml"
            IO.File.Delete(path)
            SP_DBQuery2.Visibility = Windows.Visibility.Hidden
            Exit Sub
        End If

        If TypeOf db Is FluentNHibernateConnector Then
            db.LastCompany = csettings.CompanyID
            'You do this to update the table structure
            Dim temp = db.LastCompany
        Else
            db.LastCompany = _companyname
        End If


        If Not db.CategoryExists("-Alle Kategorien", usr) Then
            db.SetCategory(New Category With {.Name = "Alle Kategorien"}, usr)
            db.SetCategory(New Category With {.Name = "Nebenleistungen"}, usr)
        End If

        'TaxClass
        If rb_GerTax.IsChecked Then
            db.SaveOrUpdateTax(New TaxClass("MwSt. 19%", 19, db))
            db.SaveOrUpdateTax(New TaxClass("MwSt. 7%", 7, db))
        End If
        If rb_AusTax.IsChecked Then
            db.SaveOrUpdateTax(New TaxClass("MwSt. 20%", 20, db))
            db.SaveOrUpdateTax(New TaxClass("MwSt. 10%", 10, db))
        End If
        If cb_SampleUnits.IsChecked Then
            db.SaveOrUpdateUnit(New Unit With {.Name = "Kilogramm", .ShortName = "Kg"})
            db.SaveOrUpdateUnit(New Unit With {.Name = "Flasche(n)", .ShortName = "Fl", .UnitFormat = "0"})
            db.SaveOrUpdateUnit(New Unit With {.Name = "Stück", .ShortName = "St", .UnitFormat = "0"})
            db.SaveOrUpdateUnit(New Unit With {.Name = "Beutel", .ShortName = "Btl", .UnitFormat = "0"})
            db.SaveOrUpdateUnit(New Unit With {.Name = "Schale", .ShortName = "Sch", .UnitFormat = "0"})
            db.SaveOrUpdateUnit(New Unit With {.Name = "Kiste", .ShortName = "Ki", .UnitFormat = "0"})
            db.SaveOrUpdateUnit(New Unit With {.Name = "Meter", .ShortName = "m"})
            db.SaveOrUpdateUnit(New Unit With {.Name = "Stunde(n)", .ShortName = "h"})
            db.SaveOrUpdateUnit(New Unit With {.Name = "Glas", .ShortName = "Gl", .UnitFormat = "0"})
            db.SaveOrUpdateUnit(New Unit With {.Name = "Paket", .ShortName = "Pa", .UnitFormat = "0"})
            db.SaveOrUpdateUnit(New Unit With {.Name = "Liter", .ShortName = "Ltr"})
        End If
        If cb_SampleCustomer.IsChecked Then
            For Each c In Customer.GenerateSampleCustomers()
                db.SaveOrUpdateCustomer(c, usr)
            Next
        End If
        If cb_SampleArticles.IsChecked AndAlso cb_SampleUnits.IsChecked AndAlso Not rb_noTax.IsChecked Then
            For Each a In Article.GenerateSampleArticles(db)
                db.SaveOrUpdateArticle(a, usr)
            Next
        End If

        db.ReloadAllDatabases()
        _usr = usr
        _db = db
        SP_DBQuery2.Visibility = Windows.Visibility.Hidden
        RaiseEvent DatabaseSet()
    End Sub

    Private Sub DatabaseConnected(db As IDatabase)
        lbl_connectionfailed.Visibility = Windows.Visibility.Collapsed
        lbl_connectionworks.Visibility = Windows.Visibility.Visible
        SP_DBQuery.Visibility = Windows.Visibility.Hidden
    End Sub

    Private Sub DatabaseNotConnected(db As IDatabase)
        lbl_connectionfailed.Visibility = Windows.Visibility.Visible
        lbl_connectionworks.Visibility = Windows.Visibility.Collapsed
        tabcontrol.SelectedValue = dbtab
        SP_DBQuery.Visibility = Windows.Visibility.Hidden
        IO.File.Delete(System.AppDomain.CurrentDomain.BaseDirectory() + "\database.xml")
    End Sub

    Private Sub tb_localdbdirectory_MouseDoubleClick(sender As Object, e As MouseButtonEventArgs) Handles tb_localdbdirectory.MouseDoubleClick
        Dim f As New Forms.FolderBrowserDialog
        f.ShowNewFolderButton = True
        If f.ShowDialog = Forms.DialogResult.OK Then
            tb_localdbdirectory.Text = f.SelectedPath
        End If
    End Sub
End Class
